package com.mobulasoft.calquest.view;

import com.mobulasoft.calquest.R;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

public class MatrixView extends View {
	

	private static final String LOG_TAG = "MatrixView";
	
	private static final int DEFAULT_CELLSIZE = 60;
	private static final int DEFAULT_HEIGHT = 20;
	private static final int DEFAULT_WIDTH = 20;
	
	private static final int GRID_COLOR = Color.RED;

	private int columns;
	private int rows;
	private int cellSize;
	
	public MatrixView(Context context) {
		super(context);
	}
	
	public MatrixView(Context context, AttributeSet attributeSet) {
		super(context, attributeSet);
		init(attributeSet);
	}
	
	public MatrixView(Context context, AttributeSet attributeSet, int defStyle) {
		super(context, attributeSet, defStyle);
		init(attributeSet);
	}
	
	private void init(AttributeSet attributeSet) {
		Log.d(LOG_TAG, "Init MatrixView from XML attributes");
		TypedArray ta =getContext().obtainStyledAttributes(attributeSet,R.styleable.MatrixView);
		columns = ta.getInt(R.styleable.MatrixView_columns, DEFAULT_WIDTH);
		rows = ta.getInt(R.styleable.MatrixView_rows, DEFAULT_HEIGHT);
		cellSize = ta.getInt(R.styleable.MatrixView_cell_size, DEFAULT_CELLSIZE);
		
	}
	
	@Override
	protected void onDraw(Canvas canvas) {
		// draw grid
		drawGrid(canvas);
		//TODO: draw cells
	}
	
	private void drawGrid(Canvas canvas) {
		Log.d(LOG_TAG, "Drawing gridi");
		Paint paint = new Paint();
		paint.setColor(GRID_COLOR);
		
		float width = getWidth();
		int height = getMeasuredHeight();
		
		// draw columns
		float x = 0f;
		for (int i = 0; i < columns+1; i++) {
			canvas.drawLine(x, 0, x, height, paint);
			x += cellSize;
		}
		// draw rows
		float y = 0f;
		for (int i = 0; i < rows+1; i++) {
			canvas.drawLine(0, y, width, y, paint);
			y += cellSize;
		}
	}
	
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		int width = cellSize * columns + 2;
		int height = cellSize * rows + 2;
		setMeasuredDimension(width, height);
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		return super.onTouchEvent(event);
		//TODO:
		// 1- calculate on which cell user touched
		// 2- find if touched cell is neighbour of last cell
		// (last cell should have initial value of the cell where game is started)
		// if not neighbour return,  neighbour of last cell:
		// 2.1- find neighbouring direction and find operator
		// 2.2- apply operator to the last touched cell
		// 2.3- set last cell to touched cell
		// 2.4- write value of 2.2 to last cell
	}


}
